<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Shop\Cart;

class CartController extends Controller
{
    /***
     * 购物车列表
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        return response()->json(Cart::all_carts());
    }


    /***
     * 将商品加入购物车
     * @param Request $request
     */
    public function store(Request $request)
    {
        $customer_id = auth('api')->user()->id;
        //接收商品的id
        $good_id = $request->good_id;
        $cart = Cart::where('good_id', $good_id)->where('customer_id', $customer_id)->first();

        //判断购物车是否有此商品，如果有，那么 数量+1
        if ($cart) {
            Cart::where('id', $cart->id)->increment('num');
            return;
        }

        //否则购物车表，创建新数据
        Cart::create([
            'good_id' => $request->good_id,
            'customer_id' => $customer_id
        ]);
    }

    /***
     * 改变数量
     * @param Request $request
     * @return array
     */
    public function change_num(Request $request)
    {
        if ($request->type == 'add') {
            Cart::where('id', $request->id)->increment('num');
        } else {
            Cart::where('id', $request->id)->decrement('num');
        }

        return response()->json(Cart::all_carts());
    }

    /***
     * ajax删除商品
     * @param Request $request
     * @return array
     */
    public function destroy(Request $request)
    {
        Cart::destroy($request->id);
        return response()->json(Cart::all_carts());
    }
}
